<template>
    <div class="page">
        <div class="wrapBageSet">
            <p class="wrapBageSet-title">
                规则说明:
            </p>
            <p class="wrapBageSet-list">
                1、发起砍价者分享给任意老粉丝帮砍，一人一次仅算一刀，拉新的新粉丝帮砍，一人一次算N刀;<br>
                2、老粉丝帮砍显示的金额数值为：每刀平均金额=可砍金额/（需砍次数-第一刀次数），老用户每刀砍价的金额在每刀平均金额的0.6-1.4<br>
                范围内的随机数;<br>
                3、当帮砍用户为新用户时，随机砍价金额还要再乘于N倍显示;<br>
                4、最后一刀，显示当前剩余金额值;
            </p>
            <p class="wrapBageSet-title">
                规则设置:
            </p>
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
                :label-position="'right'"
            >
                <el-form-item
                    label="门槛条件:"
                >
                    <div class="wrap-time">
                        <el-radio
                            v-model="code"
                            label="1"
                        >
                            仅精英用户
                        </el-radio>
                        <p
                            class="wrap-time-text"
                            style="margin-left: -15px"
                        >
                            *仅精英用户，只有当用户为精英时，可发起商品砍价活动
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    label="砍价持续时间:"
                    prop="expire_second"
                >
                    <div class="wrap-time">
                        <el-input-number
                            v-model="exprice.date"
                            controls-position="right"
                            :min="0"
                            :max="5"
                            size="small"
                            v-inserted
                            class="wrap-time-day"
                        />
                        <p class="wrap-time-dw">(天)</p>
                        <el-time-picker
                            v-model="exprice.second"
                            :picker-options="{
                                selectableRange: '00:00:00 - 23:59:59'
                            }"
                            placeholder="任意时间点"
                            size="small"
                            :style="{width: '236px'}"
                        />
                        <p class="wrap-time-dw">(小时)</p>
                        <p
                            class="wrap-time-text"
                            style="margin-left: -7px"
                        >
                            *自用户发起砍价到砍价截止的时间
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    label="发起砍价次数:"
                    prop="apply_limit_day"
                >
                    <div class="wrap-time">
                        <el-input
                            v-model="ruleForm.apply_limit_day"
                            placeholder="请输入砍价次数"
                            size="small"
                            v-inserted
                            max="10"
                            min="1"
                            maxlength="2"
                            :style="{width: '236px'}"
                        />
                        <p class="wrap-tips">
                            次/人/天
                        </p>
                        <p class="wrap-time-text">
                            *低于原价时，成功购买该商品计作一次，最多10次
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    label="帮砍次数:"
                    prop="help_limit_day"
                >
                    <div class="wrap-time">
                        <el-input
                            v-model="ruleForm.help_limit_day"
                            placeholder="请输入帮砍次数"
                            size="small"
                            v-inserted
                            max="10"
                            min="1"
                            maxlength="2"
                            :style="{width: '236px'}"
                        />
                        <p class="wrap-tips">
                            次/人/天
                        </p>
                        <p class="wrap-time-text">
                            *每个用户可帮好友砍价的次数，单个商品仅限帮砍一刀，最多10次
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    label="拉新福利:"
                    prop="new_student_bargain_weight"
                >
                    <div class="wrap-time">
                        <el-input
                            v-model="ruleForm.new_student_bargain_weight"
                            placeholder="请输入拉新福利"
                            size="small"
                            v-inserted
                            max="10"
                            min="1"
                            maxlength="2"
                            :style="{width: '236px'}"
                        />
                        <p class="wrap-tips-add">
                            倍
                        </p>
                        <p class="wrap-time-text">
                            *老粉丝帮砍一刀，新粉丝是他的【N，即设置的倍数】倍，砍的金额也是老粉丝的N倍
                        </p>
                    </div>
                </el-form-item>
                <el-form-item
                    label="精英福利:"
                    prop="stuagent_bargain_cut_down_rate"
                >
                    <div class="main">
                        <div
                            v-for="(item,index) in ruleForm.stuagent_bargain_cut_down_rate"
                            :key="index"
                            class="main-list"
                        >
                            <p class="main-list-text">
                                L{{ index + 1 }}精英少砍
                            </p>
                            <el-input
                                v-model="ruleForm.stuagent_bargain_cut_down_rate[index]"
                                size="small"
                                v-inserted
                                :style="{width: '150px'}"
                            />
                            <p class="main-list-rate">
                                %
                            </p>
                            <p
                                v-if="index == 0"
                                class="main-list-tips"
                            >
                                *减少的是砍价的次数，计算时按向下取整
                            </p>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <div style="margin-bottom: 32px">
            <el-button
                type="default"
                size="small"
                :style="{width: '126px', height: '36px', marginRight: '52px', marginLeft: '154px'}"
                @click="getConfig()"
            >
                重置
            </el-button>
            <el-button
                type="primary"
                size="small"
                :style="{width: '126px', height: '36px'}"
                @click="setConfig('ruleForm')"
            >
                保存
            </el-button>
        </div>
    </div>
</template>

<script>
export default {
    data () {
        const validateLimit = (rule, value, callback) => {
            if (value > 10) {
                callback(new Error('最多只可以发起砍价10次'));
            } else {
                callback();
            }
        };
        const validateHelpLimit = (rule, value, callback) => {
            if (value > 10) {
                callback(new Error('最多只可以帮砍10次'));
            } else {
                callback();
            }
        };

        const validateRate = (rule, value, callback) => {
            let flag = true;

            for(let key=0; key<value.length; key++){
                if(value[key] == '') {
                    flag = false;
                }
            }
            if(flag) {
                callback();
            } else {
                callback(new Error('精英福利不可以为空'));
            }
        };

        return {
            exprice: {
                date: '',// 天数
                second: ''//小时
            },
            ruleForm: {
                expire_second: '',//砍价持续时间
                apply_limit_day: '',//发起砍价次数
                help_limit_day: '',//帮助砍价次数
                new_student_bargain_weight: '',//新用户砍价权重
                stuagent_bargain_cut_down_rate: []
            },
            rules: {
                expire_second: [
                    { required: true, message: '请选择砍价持续时间', trigger: 'change' }
                ],
                apply_limit_day: [
                    { validator: validateLimit, trigger: 'change' },
                    { required: true, message: '请输入发起砍价次数', trigger: 'change' }
                ],
                help_limit_day: [
                    { validator: validateHelpLimit, trigger: 'change' },
                    { required: true, message: '请输入帮砍次数', trigger: 'change' }
                ],
                new_student_bargain_weight: [
                    { required: true, message: '请输入拉新福利', trigger: 'change' }
                ],
                stuagent_bargain_cut_down_rate: [
                    { validator: validateRate, trigger: 'change' },
                    { required: true, message: '请输入精英福利', trigger: 'change' }
                ]
            },
            code: '1'
        };
    },
    directives: {
        inserted (el, binding, vnode, oldVnode) {
            el.addEventListener("keypress", e => {
                let event = e || window.event;
                let charcode = typeof event.charCode === 'number' ? event.charCode : event.keyCode;
                let re = /\d/;

                if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !event.ctrlKey){
                    if(event.preventDefault){
                        event.preventDefault();
                    }else{
                        event.returnValue = false;
                    }
                }
            });
        }
    },
    watch: {
        exprice: {
            handler: function (val, oldVal) {//处理持续时间选择
                let dateTemp = Number(val.date) * 86400;
                let screndHous = new Date(val.second).getHours();
                let screndMinut = new Date(val.second).getMinutes();
                let scrend = new Date(val.second).getSeconds();
                let expire_second = dateTemp + screndHous * 60 * 60 + screndMinut * 60 + scrend;

                this.$set(this.ruleForm, 'expire_second', expire_second);
                // console.log(dateTemp, screndHous, screndMinut, scrend);
            },
            deep: true
        }
    },
    created () {
        this.getConfig();
    },
    methods: {
        /**
         * 获取砍价配置
         */
        getConfig () {
            this.$post('/student/shop_goods_bargain%5Cget_config',{},resp=>{
                if (resp.code == 1) {
                    this.ruleForm = {
                        expire_second: resp.data.expire_second,
                        apply_limit_day: resp.data.apply_limit_day,
                        help_limit_day: resp.data.help_limit_day,
                        new_student_bargain_weight: resp.data.new_student_bargain_weight,
                        stuagent_bargain_cut_down_rate: []
                    };

                    //处理精英福利数据
                    let rate = resp.data.stuagent_bargain_cut_down_rate;

                    for(let key in rate) {
                        if(key > 0) {
                            this.ruleForm.stuagent_bargain_cut_down_rate.push(rate[key]);
                        }
                    }

                    // 持续砍价时间处理
                    if(resp.data.expire_second == 86400) {
                        this.$set(this.exprice, 'second', this.getDate(0));
                        this.$set(this.exprice, 'date', 1);
                    } else if (resp.data.expire_second < 86400) {
                        let time = this.minuteFormate(resp.data.expire_second, false);

                        this.$set(this.exprice, 'date', 0);
                        this.$set(this.exprice, 'second', time );
                    } else if (resp.data.expire_second > 86400) {
                        let time = this.minuteFormate(resp.data.expire_second, true);

                        this.$set(this.exprice, 'date', Math.floor(resp.data.expire_second / 60 / 60 / 24));
                        this.$set(this.exprice, 'second', time );
                    }
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 设置砍价配置
         */
        setConfig (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let stuagent_bargain_cut_down_rate = {};

                    this.ruleForm.stuagent_bargain_cut_down_rate.forEach((option,index) => {
                        stuagent_bargain_cut_down_rate[index + 1] = option;
                    });

                    this.$post('/student/shop_goods_bargain%5Cset_config',{
                        expire_second: this.ruleForm.expire_second,
                        apply_limit_day: Number(this.ruleForm.apply_limit_day),
                        help_limit_day: Number(this.ruleForm.help_limit_day),
                        new_student_bargain_weight: Number(this.ruleForm.new_student_bargain_weight),
                        stuagent_bargain_cut_down_rate: JSON.stringify(stuagent_bargain_cut_down_rate)
                    },resp=>{
                        if (resp.code == 1) {
                            this.$message({
                                type: 'success',
                                message: '保存成功'
                            });
                            this.getConfig();
                        } else if (resp.code == 0) {
                            this.$message({
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 指定范围时间戳转换小时/分钟/秒
         * @param   {val}           Number      //时间戳
         * @param   {Booleanc}      type        //false:小时/分钟/秒  true:天/小时/分钟/秒
         */
        minuteFormate(val, type){
            let now_time = this.getDate(0);

            if(!type) {
                let min_total = Math.floor(val / 60);
                let sec = Math.floor(val % 60);

                if(min_total < 60){
                    return min_total * 60 * 1000 + sec * 1000 + now_time;
                }else{
                    let hour_total = Math.floor(min_total / 60);
                    let min = Math.floor(min_total % 60);

                    return hour_total * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + now_time;
                }
            } else {
                let hous = Math.floor(val / 60 / 60 / 24);
                let scend = val - hous * 86400;
                let min_total = Math.floor(scend / 60);
                let sec = Math.floor(scend % 60);

                if(min_total < 60){
                    return min_total * 60 * 1000 + sec * 1000 + now_time;
                }else{
                    let hour_total = Math.floor(min_total / 60);
                    let min = Math.floor(min_total % 60);

                    return hous * 24 * 60 * 60 * 1000 + hour_total * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + now_time;
                }
            }
        },

        /**
         * 获取指定日期时间戳
         */
        getDate (day) {
            let tempDate = new Date();
            let retult_milliseconds = tempDate.getTime() + 1000 * 60 * 60 * 24 * day;

            tempDate.setTime(retult_milliseconds);

            let result_Year = tempDate.getFullYear(),
                result_Month = (tempDate.getMonth() + 1).toString(),
                result_Date = tempDate.getDate().toString();

            if (result_Month.length === 1) {
                result_Month = "0" + result_Month;
            }

            if (result_Date.length === 1) {
                result_Date = "0" + result_Date;
            }

            let date = result_Year + "-" + result_Month + "-" + result_Date + " " + "00:00:00";

            return new Date(date).getTime();
        }
    }
};
</script>

<style lang="less" scoped>
.page {
    width: 100%;
}
.wrapBageSet {
    width: calc(100% - 64px);
    margin: 24px 32px;
    background:rgba(251,251,251,1);
    border-radius:2px;
    border:1px solid rgba(238,238,238,1);
    box-sizing: border-box;
    padding: 12px 32px 0px 32px;
    &-title {
        width: 100%;
        color: #333333;
        font-size: 14px;
        font-weight: 500;
        height: 38px;
        line-height: 38px;
        border-bottom: 1px #E9E9E9 solid;
        margin-bottom: 24px;
    }
    &-list {
        width: 899px;
        padding: 16px 24px;
        box-sizing: border-box;
        color: #333333;
        font-size: 14px;
        letter-spacing: 0px;
        background:rgba(247,247,247,1);
        border-radius:4px;
        border:1px solid rgba(220,223,230,1);
        line-height: 22px;
        margin-bottom: 48px;
    }
    .wrap-time {
        height: 32px;
        display: flex;
        align-items: center;
        &-text {
            color: #999999;
            font-size: 14px;
            margin-left: 24px;
        }
        &-dw {
            color: #999999;
            font-size: 14px;
            margin-right: 24px;
            margin-left: 5px;
        }
        .wrap-tips, .wrap-tips-add {
            color: #999999;
            font-size: 14px;
            margin-left: -60px;
            position: relative;
            z-index: 10;
        }
        .wrap-tips-add {
            margin-left: -22px;
        }
    }
    .main {
        width: 777px;
        height: 384px;
        background: rgba(247,247,247,1);
        border: 1px solid rgba(220,223,230,1);
        box-sizing: border-box;
        padding: 24px 26px;
        display: flex;
        flex-direction: column;
        &-list {
            display: flex;
            align-items: center;
            height: 36px;
            margin-bottom: 24px;
            &-text {
                color: #333333;
                font-size: 14px;
                margin-right: 16px;
            }
            &-rate {
                color: #999999;
                font-size: 14px;
                margin-left: -20px;
                position: relative;
                z-index: 10;
            }
            &-tips {
                color: #999999;
                font-size: 14px;
                margin-left: 25px;
            }
        }
    }
}
</style>

<style lang="less">
.wrapBageSet {
    .el-form-item__label {
        line-height: 32px;
    }
    .wrap-time-day .el-input__inner {
        pointer-events: none;
    }
}
</style>>
